import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/app_constants.dart';

class StorageService {
  static StorageService? _instance;
  static SharedPreferences? _preferences;

  StorageService._();

  static Future<StorageService> getInstance() async {
    _instance ??= StorageService._();
    _preferences ??= await SharedPreferences.getInstance();
    return _instance!;
  }

  // 保存字符串
  Future<bool> setString(String key, String value) async {
    return await _preferences!.setString(key, value);
  }

  // 获取字符串
  String? getString(String key, {String? defaultValue}) {
    return _preferences!.getString(key) ?? defaultValue;
  }

  // 保存整数
  Future<bool> setInt(String key, int value) async {
    return await _preferences!.setInt(key, value);
  }

  // 获取整数
  int? getInt(String key, {int? defaultValue}) {
    return _preferences!.getInt(key) ?? defaultValue;
  }

  // 保存布尔值
  Future<bool> setBool(String key, bool value) async {
    return await _preferences!.setBool(key, value);
  }

  // 获取布尔值
  bool? getBool(String key, {bool? defaultValue}) {
    return _preferences!.getBool(key) ?? defaultValue;
  }

  // 保存双精度浮点数
  Future<bool> setDouble(String key, double value) async {
    return await _preferences!.setDouble(key, value);
  }

  // 获取双精度浮点数
  double? getDouble(String key, {double? defaultValue}) {
    return _preferences!.getDouble(key) ?? defaultValue;
  }

  // 保存字符串列表
  Future<bool> setStringList(String key, List<String> value) async {
    return await _preferences!.setStringList(key, value);
  }

  // 获取字符串列表
  List<String>? getStringList(String key, {List<String>? defaultValue}) {
    return _preferences!.getStringList(key) ?? defaultValue;
  }

  // 保存JSON对象
  Future<bool> setJson(String key, Map<String, dynamic> value) async {
    final jsonString = json.encode(value);
    return await setString(key, jsonString);
  }

  // 获取JSON对象
  Map<String, dynamic>? getJson(String key) {
    final jsonString = getString(key);
    if (jsonString != null) {
      try {
        return json.decode(jsonString) as Map<String, dynamic>;
      } catch (e) {
        return null;
      }
    }
    return null;
  }

  // 删除指定键
  Future<bool> remove(String key) async {
    return await _preferences!.remove(key);
  }

  // 清除所有数据
  Future<bool> clear() async {
    return await _preferences!.clear();
  }

  // 检查键是否存在
  bool containsKey(String key) {
    return _preferences!.containsKey(key);
  }

  // 获取所有键
  Set<String> getKeys() {
    return _preferences!.getKeys();
  }

  // 应用特定的存储方法
  
  // 保存当前Wiki ID
  Future<bool> setCurrentWikiId(String wikiId) async {
    return await setString(AppConstants.keyCurrentWikiId, wikiId);
  }

  // 获取当前Wiki ID
  String getCurrentWikiId() {
    return getString(AppConstants.keyCurrentWikiId, 
        defaultValue: AppConstants.defaultWikiId) ?? AppConstants.defaultWikiId;
  }

  // 保存当前Wiki URL
  Future<bool> setCurrentWikiUrl(String url) async {
    return await setString(AppConstants.keyCurrentWikiUrl, url);
  }

  // 获取当前Wiki URL
  String getCurrentWikiUrl() {
    return getString(AppConstants.keyCurrentWikiUrl, 
        defaultValue: AppConstants.defaultWikiUrl) ?? AppConstants.defaultWikiUrl;
  }

  // 保存用户数据
  Future<bool> setUserData(Map<String, dynamic> userData) async {
    return await setJson(AppConstants.keyUserData, userData);
  }

  // 获取用户数据
  Map<String, dynamic>? getUserData() {
    return getJson(AppConstants.keyUserData);
  }

  // 保存搜索历史
  Future<bool> addSearchHistory(String query) async {
    final history = getStringList(AppConstants.keySearchHistory, defaultValue: []) ?? [];
    if (!history.contains(query)) {
      history.insert(0, query);
      // 限制历史记录数量
      if (history.length > 20) {
        history.removeLast();
      }
      return await setStringList(AppConstants.keySearchHistory, history);
    }
    return true;
  }

  // 获取搜索历史
  List<String> getSearchHistory() {
    return getStringList(AppConstants.keySearchHistory, defaultValue: []) ?? [];
  }

  // 清除搜索历史
  Future<bool> clearSearchHistory() async {
    return await remove(AppConstants.keySearchHistory);
  }

  // 移除单个搜索历史项
  Future<bool> removeSearchHistory(String query) async {
    final history = getStringList(AppConstants.keySearchHistory, defaultValue: []) ?? [];
    if (history.contains(query)) {
      history.remove(query);
      return await setStringList(AppConstants.keySearchHistory, history);
    }
    return true;
  }
  
  // 收藏功能
  
  // 添加到收藏
  Future<bool> addToFavorites(String itemId) async {
    final favorites = getStringList(AppConstants.keyFavorites, defaultValue: []) ?? [];
    if (!favorites.contains(itemId)) {
      favorites.add(itemId);
      return await setStringList(AppConstants.keyFavorites, favorites);
    }
    return true;
  }
  
  // 从收藏中移除
  Future<bool> removeFromFavorites(String itemId) async {
    final favorites = getStringList(AppConstants.keyFavorites, defaultValue: []) ?? [];
    if (favorites.contains(itemId)) {
      favorites.remove(itemId);
      return await setStringList(AppConstants.keyFavorites, favorites);
    }
    return true;
  }
  
  // 获取收藏列表
  List<String> getFavorites() {
    return getStringList(AppConstants.keyFavorites, defaultValue: []) ?? [];
  }
  
  // 清除收藏
  Future<bool> clearFavorites() async {
    return await remove(AppConstants.keyFavorites);
  }
  
  // 检查是否已收藏
  bool isFavorite(String itemId) {
    final favorites = getFavorites();
    return favorites.contains(itemId);
  }
  
  // 历史记录功能
  
  // 添加到历史记录
  Future<bool> addToHistory(Map<String, dynamic> historyItem) async {
    final history = getHistory();
    
    // 移除重复项（基于URL）
    history.removeWhere((item) => item['url'] == historyItem['url']);
    
    // 添加到开头
    history.insert(0, historyItem);
    
    // 限制历史记录数量
    if (history.length > 100) {
      history.removeRange(100, history.length);
    }
    
    // 转换为JSON字符串列表保存
    final historyStrings = history.map((item) => json.encode(item)).toList();
    return await setStringList(AppConstants.keyHistory, historyStrings);
  }
  
  // 获取历史记录
  List<Map<String, dynamic>> getHistory() {
    final historyStrings = getStringList(AppConstants.keyHistory, defaultValue: []) ?? [];
    return historyStrings.map((str) {
      try {
        return json.decode(str) as Map<String, dynamic>;
      } catch (e) {
        return <String, dynamic>{};
      }
    }).where((item) => item.isNotEmpty).toList();
  }
  
  // 清除历史记录
  Future<bool> clearHistory() async {
    return await remove(AppConstants.keyHistory);
  }
  
  // 从历史记录中移除单项
  Future<bool> removeFromHistory(String url) async {
    final history = getHistory();
    history.removeWhere((item) => item['url'] == url);
    
    final historyStrings = history.map((item) => json.encode(item)).toList();
    return await setStringList(AppConstants.keyHistory, historyStrings);
  }
  
  // 应用设置功能
  
  // 保存主题模式
  Future<bool> setThemeMode(String themeMode) async {
    return await setString(AppConstants.keyThemeMode, themeMode);
  }
  
  // 获取主题模式
  String getThemeMode() {
    return getString(AppConstants.keyThemeMode, defaultValue: 'system') ?? 'system';
  }
  
  // 保存语言设置
  Future<bool> setLanguage(String language) async {
    return await setString(AppConstants.keyLanguage, language);
  }
  
  // 获取语言设置
  String getLanguage() {
    return getString(AppConstants.keyLanguage, defaultValue: 'zh') ?? 'zh';
  }
  
  // 保存网络缓存设置
  Future<bool> setNetworkCacheEnabled(bool enabled) async {
    return await setBool(AppConstants.keyNetworkCacheEnabled, enabled);
  }

  // 获取网络缓存设置
  bool getNetworkCacheEnabled() {
    return getBool(AppConstants.keyNetworkCacheEnabled, defaultValue: true) ?? true;
  }

  // 保存离线模式设置
  Future<bool> setNetworkOfflineMode(bool enabled) async {
    return await setBool(AppConstants.keyNetworkOfflineMode, enabled);
  }

  // 获取离线模式设置
  bool getNetworkOfflineMode() {
    return getBool(AppConstants.keyNetworkOfflineMode, defaultValue: false) ?? false;
  }
}

